﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace JumpAndRun.Map
{
	public class TileLayer
	{
		private int rows;
		private int columns;
		private int tileWidth;
		private int tileHeight;
		private Tile[] tiles;

		public TileLayer(Texture2D mapTexture, int tileWidth, int tileHeight)
		{
			this.rows = mapTexture.Height;
			this.columns = mapTexture.Width;
			this.tileWidth = tileWidth;
			this.tileHeight = tileHeight;
			this.tiles = new Tile[this.rows * this.columns];

			Color[] data = new Color[mapTexture.Width * mapTexture.Height];
			mapTexture.GetData<Color>(data);

			for (int i = 0; i < data.Length; i++)
			{
				// NOTICE: Can only process black white maps and one texture at the time
				Vector3 tileColor = new Color(0, 0, 0).ToVector3();
				Vector3 actualColor = data[i].ToVector3();

				if (Vector3.Distance(tileColor, actualColor) < 0.35f)
				{
					this.tiles[i] = new Tile(0);
				}
				else
				{
					this.tiles[i] = new Tile(-1);
				}
			}
		}

		public void Draw(SpriteBatch sb, Texture2D[] textures)
		{
			int texID;
			Vector2 pos = Vector2.Zero;

			for (int y = 0; y < this.rows; y++)
			{
				for (int x = 0; x < this.columns; x++)
				{
					texID = this.tiles[x + y * this.columns].TextureIndex;

					if (texID >= 0)
					{
						pos.X = ConvertUnits.ToSimUnits(x * this.tileWidth);
						pos.Y = ConvertUnits.ToSimUnits(y * this.tileHeight);

						sb.Draw(textures[texID], pos, Color.White);
					}
				}
			}
		}
	}
}
